import {
  observable,
  action,
  toJS,
} from 'mobx'
import {
  get,
  // post,
} from '../util/http'
import { topicSchema } from '../util/variable-define'

const createTopic = (data) => {
  return Object.assign({}, topicSchema, data)
}

export class Topic {

}

export class TopicStore {
  @observable topics
  @observable detail

  constructor() {
    this.topics = []
    this.detail = {}
  }

  @action fetchTopics() {
    return new Promise((resolve, reject) => {
      if (this.topics.length > 0) {
        resolve()
      } else {
        this.topics = []
        get('./topic-list.json', {

        }).then(resp => {
          if (resp.success) {
            const topics = resp.data.map(topic => {
              return createTopic(topic)
            })
            this.topics = topics
            resolve()
          } else {
            reject()
          }
        }).catch(err => {
          reject(err)
        })
      }
    })
  }

  @action getTopicDetail(topicId) {
    return new Promise((resolve, reject) => {
      if (this.topics.length > 0) {
        resolve()
      } else {
        get('./topic-list.json', {

        }).then(resp => {
          if (resp.success) {
            const detail = resp.data.find((item, index) => {
              return item.id === topicId
            })
            this.detail = createTopic(detail)
            resolve()
          } else {
            reject()
          }
        }).catch(err => {
          reject(err)
        })
      }
    })
  }

  toJSON() {
    return {
      topics: toJS(this.topics)
    }
  }
}

export default TopicStore
